import {apiUtils} from "../web/api/ApiUtils";
import {globalConfig} from "../config/globalConfig";
import AchievementItem from "./AchievementItem";
import {model} from "../web/model/Model";
import {COMMON_CID} from "../web/model/UserModel";
import Grade from "./grade";

const {ccclass, property} = cc._decorator;

@ccclass
export default class AchievementBoard extends cc.Component {
  @property(cc.Prefab)
  private achievementItemPrefab: cc.Prefab = null;
  @property(cc.Node)
  private content: cc.Node = null
  @property(cc.Label)
  labelDiamond: cc.Label = null;
  @property(cc.Label)
  labelCoin: cc.Label = null;
  @property(Grade)
  grade: Grade = null

  private achievementItemMap = new Map();
  private achievementItems: [AchievementItem] = []
  private achievementData: Array<any> = []

  async onLoad() {
    globalConfig.segment.forEach(value => {
      const achievementItem = cc.instantiate(this.achievementItemPrefab).getComponent(AchievementItem)
      achievementItem.node.active = false;
      achievementItem.node.on('on-get', () => {
        model.user.msg.level++;
        this.grade.addGrade()
      }, this)
      this.content.addChild(achievementItem.node)
      this.achievementItemMap.set(value.id, value)
      this.achievementItems.push(achievementItem)
      this.achievementData.push(value)
      value.sort = value.id % 20000
      value.isGet = true
    })
    // console.log(Date.now() - start);
    // const testRes = {
    //   task: [
    //     {
    //       taskid: 20001,
    //       count: 10
    //     },
    //     {
    //       taskid: 20002,
    //       count: 10
    //     },
    //     {
    //       taskid: 20003,
    //       count: 10
    //     },
    //     {
    //       taskid: 20004,
    //       count: 20
    //     },
    //   ]
    // }
    // this.initServerData(testRes.task)
    // this.grade.setGrade(22)
    this.grade.setGrade(model.user.msg.level)
    const res = await apiUtils.reqAchievement()
    // console.log(Date.now() - startReq);
    this.initServerData(res.task)
    model.user.bind(this.labelCoin, COMMON_CID.COIN)
    model.user.bind(this.labelDiamond, COMMON_CID.DIAMOND)
  }

  onDestroy() {
    model.user.unbind(this.labelCoin)
    model.user.unbind(this.labelDiamond)
  }

  initServerData(tasks: Array<any>) {
    tasks.forEach(value => {
      const achievementItemData = this.achievementItemMap.get(value.taskid)
      achievementItemData.current = value.count;
      achievementItemData.isGet = false
      achievementItemData.sort -= 100
      if (achievementItemData.current >= achievementItemData.target) {
        achievementItemData.sort -= 1000
      }
    })
    this.achievementData.sort((a, b) => a.sort - b.sort)
    this.achievementItems.forEach((value, index) => {
      value.setInitData(this.achievementData[index], index)
      value.node.active = true
    })
  }

  onReturnTouch() {
    cc.director.loadScene('menu')
  }
}